package com.smart.translator.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.BroadcastReceiver;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import com.smart.translator.MainActivity;
import com.smart.translator.R;
import com.smart.translator.ble.BleManager;
import com.smart.translator.ble.AudioProcessor;
import android.util.Log;
import android.os.Handler;
import android.os.Looper;
import android.content.SharedPreferences;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.content.pm.ServiceInfo;

public class BleForegroundService extends Service {
    private static final String TAG = "BleForegroundService";
    private static final int NOTIFICATION_ID = 1001;
    private static final String CHANNEL_ID = "ble_service_channel";
    private static final String CHANNEL_NAME = "BLE连接服务";
    
    // WebSocket相关
    private static final String WS_PATH = "/ws/speech_v2";
    private static final String WS_PATH_V3 = "/ws/speech_v3";
    private static final int MAX_RETRIES = 3;
    private int wsRetryCount = 0;
    private Handler wsRetryHandler = new Handler(Looper.getMainLooper());
    private Runnable wsRetryRunnable;
    
    // 心跳相关
    private Handler heartbeatHandler = new Handler(Looper.getMainLooper());
    private Runnable heartbeatRunnable;
    private static final long HEARTBEAT_INTERVAL = 30000; // 30秒心跳间隔
    
    // 设置相关
    private static final String PREFS_SWITCH = "switch_prefs";
    private static final String KEY_USE_SPEECH_V3_SWITCH = "use_speech_v3_switch";
    private boolean useSpeechV3 = true;
    
    private PowerManager.WakeLock wakeLock;
    private boolean isServiceRunning = false;
    private BleManager bleManager;
    private AudioProcessor audioProcessor;
    
    // 广播接收器
    private BroadcastReceiver ttsReceiver;
    
    // 服务状态
    private static boolean isServiceActive = false;
    private static BleForegroundService instance = null;

    // 在类成员变量区添加
    private String lastSentAsrText = "";

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        createNotificationChannel();
        acquireWakeLock();
        isServiceRunning = true;
        isServiceActive = true;
        
        // 注册TTS广播接收器
        registerTtsReceiver();
        
        Log.d(TAG, "BLE前台服务已创建");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "BLE前台服务启动命令");
        
        // 创建通知
        Notification notification = createNotification();
        
        // 启动前台服务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10及以上使用startForegroundService，并指定前台服务类型
            startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION);
        } else {
            startForeground(NOTIFICATION_ID, notification);
        }
        
        // 加载设置
        loadSettings();
        
        // 初始化音频处理器
        initAudioProcessor();
        
        // 初始化BLE管理器
        initBleManager();
        
        // 自动连接WebSocket和TTS
        autoConnectServices();
        
        // 注释掉自动启动悬浮窗服务，避免点击设备信息时自动弹出
        //autoStartFloatWindow();
        
        return START_STICKY; // 服务被杀死后自动重启
    }
    
    /**
     * 加载设置
     */
    private void loadSettings() {
        SharedPreferences prefs = getSharedPreferences(PREFS_SWITCH, Context.MODE_PRIVATE);
        //useSpeechV3 = prefs.getBoolean(KEY_USE_SPEECH_V3_SWITCH, false);
        Log.d(TAG, "加载设置 - 使用Speech V3: " + useSpeechV3);
        
        // 加载自动连接开关状态（用于日志记录）
        boolean autoConnect = prefs.getBoolean("auto_connect_switch", false);
        Log.d(TAG, "加载设置 - 自动连接: " + autoConnect);
    }
    
    /**
     * 初始化音频处理器
     */
    private void initAudioProcessor() {
        audioProcessor = new AudioProcessor();
        audioProcessor.setContext(this);
        audioProcessor.setUseSpeechV3(useSpeechV3);
        
        // 传递WebSocket URL给AudioProcessor
        String wsUrl = buildWebSocketUrl(useSpeechV3 ? WS_PATH_V3 : WS_PATH);
        Log.d(TAG, "初始化AudioProcessor，WebSocket URL: " + wsUrl);
        audioProcessor.setWebSocketUrl(wsUrl);
        
        audioProcessor.setCallback(new AudioProcessor.AudioProcessorCallback() {
            @Override
            public void onAudioDataReceived(byte[] audioData, boolean isEndFrame) {
                //Log.d(TAG, "AudioProcessor: 音频数据准备就绪，长度: " + (audioData != null ? audioData.length : 0));
                updateNotification("音频数据: " + (audioData != null ? audioData.length : 0) + " 字节");
            }
            
            @Override
            public void onRecognitionResult(String result) {
                Log.d(TAG, "AudioProcessor: 识别结果: " + result);
                updateNotification("识别: " + result);
                // 发送ASR结果到悬浮窗
                sendAsrResultToFloatWindow(result);
            }
            
            @Override
            public void onRecognitionResult(String result, boolean isVadFinal) {
                Log.d(TAG, "AudioProcessor: 识别结果: " + result + ", VAD最终: " + isVadFinal);
                updateNotification("识别: " + result);
                // 判断当前ASR类型
                if (audioProcessor != null && audioProcessor.isUseSpeechV3() && audioProcessor.isAliyunAsr()) {
                    // Aliyun只在最终结果时发送
                    if (isVadFinal) {
                        Log.d(TAG, "Aliyun ASR最终结果，发送到悬浮窗: " + result);
                        sendAliyunAsrResultToFloatWindow(result);
                    } else {
                        Log.d(TAG, "Aliyun ASR中间结果，跳过发送: " + result);
                    }
                } else {
                    // 其它ASR逻辑不变
                    sendAsrResultToFloatWindow(result, isVadFinal);
                }
            }
            
            @Override
            public void onPcmDataProcessed(byte[] pcmData) {
                Log.d(TAG, "AudioProcessor: PCM数据处理完成，长度: " + (pcmData != null ? pcmData.length : 0));
                updateNotification("PCM处理: " + (pcmData != null ? pcmData.length : 0) + " 字节");
            }
            
            @Override
            public void onWavDataReady(byte[] wavPcmData) {
                Log.d(TAG, "AudioProcessor: WAV数据准备完成，长度: " + (wavPcmData != null ? wavPcmData.length : 0));
                updateNotification("WAV数据: " + (wavPcmData != null ? wavPcmData.length : 0) + " 字节");
            }
            
            @Override
            public void onTtsStatusChanged(boolean connected) {
                Log.d(TAG, "AudioProcessor: TTS状态变化: " + connected);
                updateNotification("TTS: " + (connected ? "已连接" : "已断开"));
            }
            
            @Override
            public void onWebSocketStatusChanged(boolean connected) {
                Log.d(TAG, "AudioProcessor: WebSocket状态变化: " + connected);
                updateNotification("WebSocket: " + (connected ? "已连接" : "已断开"));
            }
            
            @Override
            public void onAudioPlaybackStarted() {
                Log.d(TAG, "AudioProcessor: 音频播放开始");
                updateNotification("音频播放开始");
            }
            
            @Override
            public void onAudioPlaybackCompleted() {
                Log.d(TAG, "AudioProcessor: 音频播放完成");
                updateNotification("音频播放完成");
            }
            
            @Override
            public void onAudioFileSaved(String filePath) {
                Log.d(TAG, "AudioProcessor: 音频文件已保存: " + filePath);
                updateNotification("音频文件已保存");
            }
            
            @Override
            public void onEncodeTestCompleted(byte[] encodedData) {
                Log.d(TAG, "AudioProcessor: 编码测试完成，长度: " + (encodedData != null ? encodedData.length : 0));
                updateNotification("编码测试完成");
            }
            
            @Override
            public void onDecodeTestCompleted(byte[] decodedData) {
                Log.d(TAG, "AudioProcessor: 解码测试完成，长度: " + (decodedData != null ? decodedData.length : 0));
                updateNotification("解码测试完成");
            }
            
            @Override
            public void onTtsAdpcmDataReceived(byte[] adpcmData) {
                Log.d(TAG, "AudioProcessor: TTS ADPCM数据接收，长度: " + (adpcmData != null ? adpcmData.length : 0));
                updateNotification("TTS ADPCM: " + (adpcmData != null ? adpcmData.length : 0) + " 字节");
            }
        });
        
        // 启动心跳
        audioProcessor.startHeartbeat();
        
        Log.d(TAG, "音频处理器初始化完成");
    }
    
    /**
     * 初始化BLE管理器
     */
    private void initBleManager() {
        bleManager = BleManager.getInstance();
        bleManager.initialize(this);
        bleManager.setUseSpeechV3(useSpeechV3);
        
        // 将AudioProcessor设置给BleManager
        bleManager.setAudioProcessor(audioProcessor);
        
        // 设置连接监听器
        bleManager.setConnectionListener(new BleManager.BleConnectionListener() {
            @Override
            public void onConnected(android.bluetooth.BluetoothDevice device) {
                Log.d(TAG, "BLE设备连接成功: " + device.getAddress());
                updateNotification("已连接: " + device.getName());
            }
            
            @Override
            public void onDisconnected(android.bluetooth.BluetoothDevice device) {
                Log.d(TAG, "BLE设备连接断开: " + device.getAddress());
                
                // ⭐ 修复：检查是否有历史设备和自动连接设置
                SharedPreferences switchPrefs = getSharedPreferences(PREFS_SWITCH, Context.MODE_PRIVATE);
                boolean autoConnect = switchPrefs.getBoolean("auto_connect_switch", false);
                
                // 检查是否有历史设备
                SharedPreferences devicePrefs = getSharedPreferences("ble_history", Context.MODE_PRIVATE);
                String lastDeviceAddress = devicePrefs.getString("last_device", null);
                
                if (autoConnect && lastDeviceAddress != null && !lastDeviceAddress.isEmpty()) {
                    Log.d(TAG, "自动连接已开启且有历史设备，安排自动重连");
                    updateNotification("连接断开，正在重连...");
                    bleManager.setAutoReconnect(true);
                } else {
                    Log.d(TAG, "自动连接已关闭或无历史设备，不进行重连");
                    updateNotification("连接断开");
                    bleManager.setAutoReconnect(false);
                }
            }
        });
        
        // 设置数据监听器
        bleManager.setDataListener(new BleManager.BleDataListener() {
            @Override
            public void onDataReceived(java.util.UUID characteristicUuid, byte[] data) {
                //Log.d(TAG, "收到BLE数据: " + characteristicUuid + ", 长度: " + (data != null ? data.length : 0));
                // 数据已经由BleManager转发给AudioProcessor处理
            }
            
            @Override
            public void onAudioDataReceived(byte[] audioData, boolean isEndFrame) {
                Log.d(TAG, "收到音频数据: " + (audioData != null ? audioData.length : 0) + " 字节, isEndFrame: " + isEndFrame);
                // 音频数据由AudioProcessor处理
            }
            
            @Override
            public void onRecognitionResult(String result) {
                Log.d(TAG, "收到识别结果: " + result);
                // 识别结果由AudioProcessor处理
            }
        });
        
        // 检查自动连接开关状态，只有在开启时才自动连接历史设备
        SharedPreferences switchPrefs = getSharedPreferences(PREFS_SWITCH, Context.MODE_PRIVATE);
        boolean autoConnect = switchPrefs.getBoolean("auto_connect_switch", false);
        
        if (autoConnect) {
            // 如果开启了自动连接，尝试连接历史设备
            bleManager.connectToLastDevice();
            Log.d(TAG, "自动连接已开启，尝试连接历史设备");
        } else {
            Log.d(TAG, "自动连接已关闭，跳过连接历史设备");
        }
        
        Log.d(TAG, "BLE管理器初始化完成");
    }
    
    /**
     * 自动连接服务
     */
    private void autoConnectServices() {
        Log.d(TAG, "开始自动连接服务");
        
        // AudioProcessor内部会自动连接ASR和TTS
        // 延迟5秒后启动心跳
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            // 启动心跳
            startHeartbeat();
            
            updateNotification("服务已启动，等待连接...");
        }, 5000);
    }
    
    /**
     * 启动心跳
     */
    private void startHeartbeat() {
        if (heartbeatRunnable != null) {
            heartbeatHandler.removeCallbacks(heartbeatRunnable);
        }
        
        heartbeatRunnable = new Runnable() {
            @Override
            public void run() {
                sendHeartbeat();
                heartbeatHandler.postDelayed(this, HEARTBEAT_INTERVAL);
            }
        };
        
        heartbeatHandler.post(heartbeatRunnable);
        Log.d(TAG, "心跳已启动");
    }
    
    /**
     * 停止心跳
     */
    private void stopHeartbeat() {
        if (heartbeatRunnable != null) {
            heartbeatHandler.removeCallbacks(heartbeatRunnable);
            heartbeatRunnable = null;
        }
        Log.d(TAG, "心跳已停止");
    }
    
    /**
     * 发送心跳
     */
    private void sendHeartbeat() {
        Log.d(TAG, "发送心跳");
        
        // 检查BLE连接状态
        if (bleManager != null && bleManager.isConnected()) {
            Log.d(TAG, "BLE连接正常");
        } else {
            Log.w(TAG, "BLE连接异常");
        }
        
        // 检查ASR连接状态
        if (audioProcessor != null && audioProcessor.isAsrConnected()) {
            Log.d(TAG, "ASR连接正常");
        } else {
            Log.w(TAG, "ASR连接异常");
            // 注释掉自动重连
            // reconnectAsr();
        }
        
        // 检查TTS连接状态
        if (audioProcessor != null && audioProcessor.isTtsConnected()) {
            Log.d(TAG, "TTS连接正常");
        } else {
            Log.w(TAG, "TTS连接异常");
        }
        
        updateNotification("服务运行中 - BLE:" + (bleManager != null && bleManager.isConnected() ? "✓" : "✗") + 
                         " ASR:" + (audioProcessor != null && audioProcessor.isAsrConnected() ? "✓" : "✗") + 
                         " TTS:" + (audioProcessor != null && audioProcessor.isTtsConnected() ? "✓" : "✗"));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isServiceRunning = false;
        isServiceActive = false;
        instance = null;
        
        // 注销广播接收器
        if (ttsReceiver != null) {
            try {
                // 使用LocalBroadcastManager注销本地广播接收器
                LocalBroadcastManager.getInstance(this).unregisterReceiver(ttsReceiver);
                Log.d(TAG, "TTS本地广播接收器已注销");
            } catch (Exception e) {
                Log.e(TAG, "注销TTS本地广播接收器失败", e);
            }
        }
        
        // 停止心跳
        stopHeartbeat();
        
        // 清理资源
        if (audioProcessor != null) {
            audioProcessor.cleanup();
        }
        
        if (bleManager != null) {
            bleManager.cleanup();
        }
        
        releaseWakeLock();
        Log.d(TAG, "BLE前台服务已销毁");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.d(TAG, "应用任务被移除，但保持服务运行");
        // 不要停止服务，保持BLE连接
        super.onTaskRemoved(rootIntent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("BLE连接服务通知");
            channel.setShowBadge(false);
            channel.setSound(null, null);
            channel.enableVibration(false);
            
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(channel);
            }
        }
    }

    private Notification createNotification() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
            this, 0, notificationIntent,
            PendingIntent.FLAG_IMMUTABLE
        );

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("智能翻译器")
            .setContentText("BLE设备连接中...")
            .setSmallIcon(R.drawable.ic_translate)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .setAutoCancel(false)
            .setPriority(NotificationCompat.PRIORITY_LOW);

        return builder.build();
    }

    public void updateNotification(String status) {
        NotificationManager notificationManager = 
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("智能翻译器")
                .setContentText(status)
                .setSmallIcon(R.drawable.ic_translate)
                .setOngoing(true)
                .setAutoCancel(false)
                .setPriority(NotificationCompat.PRIORITY_LOW);
            
            notificationManager.notify(NOTIFICATION_ID, builder.build());
        }
    }

    private void acquireWakeLock() {
        try {
            PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
            if (powerManager != null) {
                wakeLock = powerManager.newWakeLock(
                    PowerManager.PARTIAL_WAKE_LOCK,
                    "BleForegroundService::WakeLock"
                );
                wakeLock.acquire();
                Log.d(TAG, "获取唤醒锁成功");
            }
        } catch (Exception e) {
            Log.e(TAG, "获取唤醒锁失败", e);
        }
    }

    private void releaseWakeLock() {
        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
            wakeLock = null;
            Log.d(TAG, "释放唤醒锁成功");
        }
    }

    public boolean isServiceRunning() {
        return isServiceRunning;
    }
    
    public static boolean isServiceActive() {
        return isServiceActive;
    }
    
    public static BleForegroundService getInstance() {
        return instance;
    }

    public static void startService(Context context) {
        Intent intent = new Intent(context, BleForegroundService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
        Log.d(TAG, "启动BLE前台服务");
    }
    
    private static boolean isServiceRunning(Context context) {
        try {
            android.app.ActivityManager manager = 
                (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            for (android.app.ActivityManager.RunningServiceInfo service : 
                 manager.getRunningServices(Integer.MAX_VALUE)) {
                if (BleForegroundService.class.getName().equals(service.service.getClassName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "检查服务状态失败", e);
        }
        return false;
    }

    public static void stopService(Context context) {
        Intent intent = new Intent(context, BleForegroundService.class);
        context.stopService(intent);
        Log.d(TAG, "停止BLE前台服务");
    }
    
    // 获取BLE管理器实例
    public BleManager getBleManager() {
        return bleManager;
    }
    
    /**
     * 获取音频处理器
     */
    public AudioProcessor getAudioProcessor() {
        return audioProcessor;
    }
    
    /**
     * 设置接口版本
     */
    public void setUseSpeechV3(boolean useV3) {
        this.useSpeechV3 = useV3;
        if (audioProcessor != null) {
            audioProcessor.setUseSpeechV3(useV3);
        }
        if (bleManager != null) {
            bleManager.setUseSpeechV3(useV3);
        }
        
        // 保存设置
        SharedPreferences prefs = getSharedPreferences(PREFS_SWITCH, Context.MODE_PRIVATE);
        prefs.edit().putBoolean(KEY_USE_SPEECH_V3_SWITCH, useV3).apply();
        
        Log.d(TAG, "设置接口版本: " + (useV3 ? "v3" : "v2"));
    }
    
    /**
     * 获取接口版本
     */
    public boolean isUseSpeechV3() {
        return useSpeechV3;
    }
    
    /**
     * 发送TTS文本
     */
    public void sendTTSText(String text) {
        Log.d(TAG, "🎤 BleForegroundService.sendTTSText被调用: " + text);
        if (audioProcessor != null) {
            Log.d(TAG, "🎤 AudioProcessor存在，调用sendTTSText");
            audioProcessor.sendTTSText(text);
            Log.d(TAG, "✅ TTS文本已发送到AudioProcessor: " + text);
        } else {
            Log.w(TAG, "❌ AudioProcessor为空，无法发送TTS文本");
        }
    }
    
    /**
     * 连接TTS
     */
    public void connectTTS() {
        if (audioProcessor != null) {
            audioProcessor.connectTTS();
            Log.d(TAG, "连接TTS");
        }
    }
    
    /**
     * 断开TTS
     */
    public void disconnectTTS() {
        if (audioProcessor != null) {
            audioProcessor.disconnectTTS();
            Log.d(TAG, "断开TTS");
        }
    }
    
    /**
     * 获取服务状态信息
     */
    public String getServiceStatus() {
        StringBuilder status = new StringBuilder();
        status.append("BLE前台服务状态:\n");
        status.append("- 服务运行: ").append(isServiceRunning).append("\n");
        status.append("- 服务活跃: ").append(isServiceActive).append("\n");
        status.append("- 使用Speech V3: ").append(useSpeechV3).append("\n");
        
        if (bleManager != null) {
            status.append(bleManager.getConnectionStatus());
        }
        
        if (audioProcessor != null) {
            status.append("- ASR连接: ").append(audioProcessor.isAsrConnected()).append("\n");
            status.append("- TTS连接: ").append(audioProcessor.isTtsConnected()).append("\n");
        }
        
        return status.toString();
    }
    
    // 注册TTS广播接收器
    private void registerTtsReceiver() {
        ttsReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d(TAG, "📡 TTS广播接收器被调用，Action: " + intent.getAction());
                if ("com.smart.translator.TTS_SEND".equals(intent.getAction())) {
                    String text = intent.getStringExtra("text");
                    Log.d(TAG, "📡 收到TTS发送请求: " + text);
                    if (text != null && !text.isEmpty()) {
                        Log.d(TAG, "🎤 开始处理TTS文本: " + text);
                        sendTTSText(text);
                    } else {
                        Log.w(TAG, "❌ TTS文本为空，跳过处理");
                    }
                }
            }
        };
        
        IntentFilter filter = new IntentFilter("com.smart.translator.TTS_SEND");
        // 使用LocalBroadcastManager注册本地广播接收器
        LocalBroadcastManager.getInstance(this).registerReceiver(ttsReceiver, filter);
        Log.d(TAG, "📡 TTS本地广播接收器已注册");
    }
    
    // 发送ASR结果到悬浮窗
    private void sendAsrResultToFloatWindow(String asrText) {
        sendAsrResultToFloatWindow(asrText, false);
    }
    
    // 发送ASR结果到悬浮窗（带VAD最终标记）
    private void sendAsrResultToFloatWindow(String asrText, boolean isVadFinal) {
        try {
            if (isVadFinal) {
                // VAD最终结果，强制发送（跳过去重检查）
                Log.d(TAG, "🔄 VAD最终结果，强制发送到悬浮窗: " + asrText);
                //lastSentAsrText = asrText; // 更新最后发送的文本
            }
            /*
             else {
                // 普通结果，进行去重检查
                if (asrText.equals(lastSentAsrText)) {
                    Log.d(TAG, "ASR结果未变化，跳过广播: " + asrText);
                    return;
                }
                lastSentAsrText = asrText;
            }
            */
            Log.d(TAG, "准备发送ASR结果到悬浮窗: " + asrText);
            Intent intent = new Intent("com.smart.translator.ASR_RESULT");
            intent.putExtra("asr_text", asrText);
            intent.putExtra("is_vad_final", isVadFinal); // 添加VAD最终标记
            // 使用LocalBroadcastManager发送本地广播
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Log.d(TAG, "发送ASR结果到悬浮窗: " + asrText + (isVadFinal ? " (VAD最终)" : ""));
            // 检查是否有接收器注册
            Log.d(TAG, "本地广播已发送，等待悬浮窗接收...");
        } catch (Exception e) {
            Log.e(TAG, "发送ASR结果到悬浮窗失败", e);
        }
    }

    /**
     * 手动重连ASR
     */
    public void reconnectAsr() {
        if (audioProcessor != null) {
            //audioProcessor.reconnectAsr();
            Log.d(TAG, "手动重连ASR");
        }
    }

    // 自动启动悬浮窗服务
    private void autoStartFloatWindow() {
        try {
            Log.d(TAG, "自动启动悬浮窗服务");
            
            // 检查悬浮窗权限
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                if (!android.provider.Settings.canDrawOverlays(this)) {
                    Log.w(TAG, "没有悬浮窗权限，无法启动悬浮窗服务");
                    return;
                }
            }
            
            // 启动悬浮窗服务
            Intent floatIntent = new Intent(this, com.smart.translator.service.FloatWindowService.class);
            startService(floatIntent);
            Log.d(TAG, "悬浮窗服务启动请求已发送");
            
        } catch (Exception e) {
            Log.e(TAG, "自动启动悬浮窗服务失败", e);
        }
    }

    // 获取服务器地址
    private String getServerUrl() {
        try {
            android.content.SharedPreferences prefs = getSharedPreferences("app_config", Context.MODE_PRIVATE);
            return prefs.getString("server_url", "qixin.yeshan.fun");
        } catch (Exception e) {
            Log.e(TAG, "获取服务器地址失败", e);
            return "qixin.yeshan.fun";
        }
    }
    
    // 构建WebSocket URL
    private String buildWebSocketUrl(String path) {
        String serverUrl = getServerUrl();
        return "ws://" + serverUrl + path;
    }

    // 新增：专用于Aliyun最终结果的广播，带is_cloud_final参数
    private void sendAliyunAsrResultToFloatWindow(String asrText) {
        try {
            Intent intent = new Intent("com.smart.translator.ASR_RESULT");
            intent.putExtra("asr_text", asrText);
            intent.putExtra("is_cloud_final", true); // 只用于Aliyun最终结果
            
            // 使用异步广播发送，避免线程异常
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            Log.d(TAG, "发送Aliyun最终ASR结果到悬浮窗: " + asrText + " (Cloud最终)");
        } catch (Exception e) {
            Log.e(TAG, "发送Aliyun最终ASR结果到悬浮窗失败", e);
        }
    }
} 